from rest_framework import viewsets, filters
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.views import APIView
from django.http import JsonResponse
from .models import StockBasic, TradeDate, DailyData, DataUpdateRecord, ThsPlate, ThsStockPlate
from .constants import DATA_TYPES, START_KDATA_DATE
from django_filters.rest_framework import DjangoFilterBackend
from .models import StockBasic, TradeDate, DailyData, DailyBasic
from .serializers import (
    StockBasicSerializer, TradeDateSerializer, DailyDataSerializer, 
    DailyBasicSerializer, ThsPlateSerializer, ThsStockPlateSerializer
)
from .tushare_api import TushareAPI

# from data_analysis.tasks import at_start

class StockBasicViewSet(viewsets.ReadOnlyModelViewSet):
    """
    股票基本信息视图集
    """
    queryset = StockBasic.objects.all()
    serializer_class = StockBasicSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['ts_code', 'symbol', 'name', 'area', 'industry', 'market', 'list_status']
    search_fields = ['name', 'ts_code', 'symbol']
    ordering_fields = ['list_date']


class TradeDateViewSet(viewsets.ReadOnlyModelViewSet):
    """
    交易日历视图集
    """
    queryset = TradeDate.objects.all()
    serializer_class = TradeDateSerializer
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_fields = ['exchange', 'cal_date', 'is_open']
    ordering_fields = ['cal_date']

    @action(detail=False, methods=['get'])
    def latest_trade_date(self, request):
        """
        获取最新交易日
        """
        latest_date = TradeDate.objects.filter(is_open=1).order_by('-cal_date').first()
        if latest_date:
            serializer = self.get_serializer(latest_date)
            return Response(serializer.data)
        return Response({"detail": "没有找到交易日数据"}, status=404)


class DailyDataViewSet(viewsets.ReadOnlyModelViewSet):
    """
    日线行情视图集
    """
    queryset = DailyData.objects.all()
    serializer_class = DailyDataSerializer
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_fields = ['ts_code', 'trade_date']
    ordering_fields = ['trade_date', 'ts_code']

    @action(detail=False, methods=['get'])
    def latest(self, request):
        """
        获取最新日线数据
        """
        ts_code = request.query_params.get('ts_code', None)
        
        if ts_code:
            latest_data = DailyData.objects.filter(ts_code=ts_code).order_by('-trade_date').first()
            if latest_data:
                serializer = self.get_serializer(latest_data)
                return Response(serializer.data)
            return Response({"detail": f"没有找到股票 {ts_code} 的日线数据"}, status=404)
        
        # 获取最新交易日
        latest_date = TradeDate.objects.filter(is_open=1).order_by('-cal_date').first()
        if not latest_date:
            return Response({"detail": "没有找到交易日数据"}, status=404)
        
        # 获取最新交易日的所有日线数据
        latest_data = DailyData.objects.filter(trade_date=latest_date.cal_date)
        if not latest_data.exists():
            return Response({"detail": f"没有找到 {latest_date.cal_date} 的日线数据"}, status=404)
        
        page = self.paginate_queryset(latest_data)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        
        serializer = self.get_serializer(latest_data, many=True)
        return Response(serializer.data)


class DailyBasicViewSet(viewsets.ReadOnlyModelViewSet):
    """
    每日指标视图集
    """
    queryset = DailyBasic.objects.all()
    serializer_class = DailyBasicSerializer
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_fields = ['ts_code', 'trade_date']
    ordering_fields = ['trade_date', 'ts_code']

    @action(detail=False, methods=['get'])
    def latest(self, request):
        """
        获取最新每日指标数据
        """
        ts_code = request.query_params.get('ts_code', None)
        
        if ts_code:
            latest_data = DailyBasic.objects.filter(ts_code=ts_code).order_by('-trade_date').first()
            if latest_data:
                serializer = self.get_serializer(latest_data)
                return Response(serializer.data)
            return Response({"detail": f"没有找到股票 {ts_code} 的每日指标数据"}, status=404)
        
        # 获取最新交易日
        latest_date = TradeDate.objects.filter(is_open=1).order_by('-cal_date').first()
        if not latest_date:
            return Response({"detail": "没有找到交易日数据"}, status=404)
        
        # 获取最新交易日的所有每日指标数据
        latest_data = DailyBasic.objects.filter(trade_date=latest_date.cal_date)
        if not latest_data.exists():
            return Response({"detail": f"没有找到 {latest_date.cal_date} 的每日指标数据"}, status=404)
        
        page = self.paginate_queryset(latest_data)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        
        serializer = self.get_serializer(latest_data, many=True)
        return Response(serializer.data)


class TushareDataUpdateViewSet(viewsets.ViewSet):
    """
    Tushare数据更新视图集
    """
    @action(detail=False, methods=['post'])
    def update_all_data(self, request):
        """
        更新全部市场数据
        """
        print(f'get update all data comes。request.data = {request.data}')
        
        try:
            start_date = request.data.get('startDate')
            end_date = request.data.get('endDate')
            
            if not start_date or not end_date:
                return Response({
                    'status': 'error',
                    'message': '必须提供startDate和endDate参数'
                }, status=400)
                
            client = TushareAPI()
            results = client.update_all_data(start_date=start_date, end_date=end_date)
            
    
            
            return Response({
                'status': 'success',
                'message': '数据更新完成',
                'results': results,
                'start_date': start_date,
                'end_date': end_date
            })
        except Exception as e:
            return Response({
                'status': 'error',
                'message': str(e)
            }, status=500)


class ThsPlateViewSet(viewsets.ReadOnlyModelViewSet):
    """
    同花顺板块视图集
    """
    queryset = ThsPlate.objects.all()
    serializer_class = ThsPlateSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['ts_code', 'type', 'exchange']
    search_fields = ['name', 'ts_code']
    ordering_fields = ['list_date']

    @action(detail=False, methods=['get'])
    def by_type(self, request):
        """
        按板块类型获取数据
        """
        plate_type = request.query_params.get('type', None)
        if not plate_type:
            return Response({"detail": "必须提供板块类型参数"}, status=400)
            
        plates = self.queryset.filter(type=plate_type)
        if not plates.exists():
            return Response({"detail": f"没有找到类型为 {plate_type} 的板块数据"}, status=404)
            
        page = self.paginate_queryset(plates)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
            
        serializer = self.get_serializer(plates, many=True)
        return Response(serializer.data)


class ThsStockPlateViewSet(viewsets.ReadOnlyModelViewSet):
    """
    股票所属板块关系视图集
    """
    queryset = ThsStockPlate.objects.all()
    serializer_class = ThsStockPlateSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['ts_code', 'plate_code', 'plate_type', 'is_new']
    search_fields = ['plate_name']
    ordering_fields = ['in_date', 'out_date']

    @action(detail=False, methods=['get'])
    def by_stock(self, request):
        """
        获取指定股票的所有板块关系
        """
        ts_code = request.query_params.get('ts_code', None)
        if not ts_code:
            return Response({"detail": "必须提供股票代码参数"}, status=400)
            
        relations = self.queryset.filter(ts_code=ts_code)
        if not relations.exists():
            return Response({"detail": f"没有找到股票 {ts_code} 的板块关系数据"}, status=404)
            
        page = self.paginate_queryset(relations)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
            
        serializer = self.get_serializer(relations, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=['get'])
    def by_plate(self, request):
        """
        获取指定板块的所有股票关系
        """
        plate_code = request.query_params.get('plate_code', None)
        if not plate_code:
            return Response({"detail": "必须提供板块代码参数"}, status=400)
            
        relations = self.queryset.filter(plate_code=plate_code)
        if not relations.exists():
            return Response({"detail": f"没有找到板块 {plate_code} 的股票关系数据"}, status=404)
            
        page = self.paginate_queryset(relations)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
            
        serializer = self.get_serializer(relations, many=True)
        return Response(serializer.data)


class LastUpdatedDateView(APIView):
    """
    获取最后更新日期视图
    """
    def get(self, request):
        print(f'LastUpdateDateView called!')
        try:
            # 查询ALL_DATA类型的最新记录
            last_record = DataUpdateRecord.objects.filter(
                data_type=DATA_TYPES['ALL_DATA']
            ).first()
            print(f'last_record = {last_record}')
            if last_record:
                return JsonResponse({
                    'last_updated_date': last_record.last_update_date.strftime('%Y-%m-%d')
                })
            print(f'no record found')
            # 如果没有记录，返回START_KDATA_DATE
            return JsonResponse({
                'last_updated_date': START_KDATA_DATE
            })
            
        except Exception as e:
            print(f'e = {e}')
            return JsonResponse({
                'error': str(e)
            }, status=500)